﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameLib.Framework;
using GameLib.Utils;

namespace GameLib.WorldMap
{
	public class Terrain : IContentHost
	{
		public Name Name
		{
			get;
			private set;
		}

		public char Id
		{
			get;
			private set;
		}

		public override string ToString()
		{
			return string.Format("Terrain<{0}>", Name);
		}

		#region IContentHost Members

		public ContentDictionary Content
		{
			get { return m_Content; }
		}
		private ContentDictionary m_Content = new ContentDictionary();

		#endregion
	}

	public class TerrainCollection : ICollection<Terrain>
	{
		public Terrain DefaultTerrain
		{
			get;
			private set;
		}

		public Terrain Find(char id)
		{
			Terrain terrain = null;
			m_Terrains.TryGetValue(id, out terrain);
			return terrain;
		}

		#region ICollection<Terrain> Members

		public void Add(Terrain item)
		{
			if (m_Terrains.ContainsKey(item.Id))
				throw new Exception(string.Format("Terrain with id {0} already exists: {1}, now adding {2}", item.Id, m_Terrains[item.Id], item));

			if (m_Terrains.Count == 0)
				DefaultTerrain = item;

			m_Terrains[item.Id] = item;
		}

		public void Clear()
		{
			DefaultTerrain = null;
			m_Terrains.Clear();
		}

		public bool Contains(Terrain item)
		{
			return m_Terrains.ContainsValue(item);
		}

		public void CopyTo(Terrain[] array, int arrayIndex)
		{
			m_Terrains.Values.CopyTo(array, arrayIndex);
		}

		public int Count
		{
			get { return m_Terrains.Count; }
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public bool Remove(Terrain item)
		{
			if (m_Terrains.Remove(item.Id))
			{
				if (item == DefaultTerrain)
				{
					DefaultTerrain = null;
					foreach (Terrain terrain in m_Terrains.Values)
					{
						DefaultTerrain = terrain;
						break;
					}
				}
				return true;
			}
			else
			{
				return false;
			}			
		}

		#endregion

		#region IEnumerable<Terrain> Members

		public IEnumerator<Terrain> GetEnumerator()
		{
			return m_Terrains.Values.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		#endregion

		private Dictionary<char, Terrain> m_Terrains = new Dictionary<char, Terrain>();
		//static Random rand = new Random();
	}
}
